# -*- coding: utf-8 -*-
__author__ = 'YinDu'

from routes import api_v
from utils.RequestTool import *
from utils.ProjectTool import *

app = Flask(__name__)

# 保留flask原生异常处理
handle_exception = app.handle_exception
handle_user_exception = app.handle_user_exception


def _access_control(response):
    """
    解决跨域请求
    """
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET,HEAD,PUT,PATCH,POST,DELETE'
    response.headers['Access-Control-Allow-Headers'] = 'Authorization,content-type'
    response.headers['Access-Control-Max-Age'] = 86400
    return response


def create_app(config):
    """
    创建app
    """
    # 添加配置
    app.config.from_object(config)
    # 解决跨域
    app.after_request(_access_control)
    # 注册蓝图
    app.register_blueprint(api_v)
    # 使用flask原生异常处理程序
    app.handle_exception = handle_exception
    app.handle_user_exception = handle_user_exception

    return app


# 钩子函数
@app.before_request
def before_requestb():
    pass


# @app.teardown_request
# def tear(e):
#     print(e)


@app.errorhandler(500)
def before_requestb(e):
    return jsonify(err_response())


@app.errorhandler(404)
def before_requestb(e):
    return jsonify(normal_response(mage='No path', code=40004, data=str(e).split(':')[1]))
